﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using MyBet.Class;
using MyBet.Helpers;
using MyBet.LoginUI;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using MyBet.Web;
using System.ServiceModel.DomainServices.Client;

namespace MyBet
{
	public partial class UserStatus : UserControl
	{

        private Storyboard _showUserInformation;
        private SecurityServiceReference.UserObject _currentUser;
        private readonly AuthenticationService authService = WebContext.Current.Authentication;
        //private UserRegistrationContext userRegistrationContext = new UserRegistrationContext();

        public delegate void Login();
        public event Login OnLogin;
        public delegate void Logout();
        public event Logout OnLogout;
        private MainPage _mainPageParent;

        public MainPage MainPageParent
        {
            get { return _mainPageParent; }
            set { _mainPageParent = value; }
        }

        public bool IsConnected
        {
            get { return (_currentUser != null); }
        }

        public SecurityServiceReference.UserObject User
        {
            get { return _currentUser; }
            set {
                _currentUser = value;
                UserInfo.User = value;
                if (value != null)
                {
                    ShowUserInformation.Begin();
                }
                UpdateLoginBtn();
            }
        }

        /// <summary>
        /// Login / Logout button label
        /// </summary>
        private void UpdateLoginBtn()
        {
            if (!IsConnected)
            {
                // no user connected => Login button
                LoginLogoutLink.Text = LangHelper.GetString("BtnLogin");
                // .Content = LangHelper.GetString("BtnLogin");
            }
            else
            {
                // user connected => Logout button
               LoginLogoutLink.Text = LangHelper.GetString("BtnLogout");
            }
            MouseLeaveStoryboard.Begin();
        }


        public Storyboard ShowUserInformation
        {
            get { return _showUserInformation; }
            set { _showUserInformation = value; }
        }

		public UserStatus()
		{
			// Required to initialize variables
			InitializeComponent();

            this.authService.LoggedIn += this.Authentication_LoggedIn;
            this.authService.LoggedOut += this.Authentication_LoggedOut;

            CreateUserInfoAnim();
		}

        void dlgConfirm_Closed(object sender, EventArgs e)
        {
            Error cw = (Error)sender;
            if (cw.DialogResult == true)
            {
                this.authService.Logout(logoutOperation =>
                {
                    if (logoutOperation.HasError)
                    {
                        ErrorWindow.CreateNew(logoutOperation.Error);
                        logoutOperation.MarkErrorAsHandled();
                    }
                }, /* userState */ null);
            }
        }

        /// <summary>
        /// Create Fade in to display user information
        /// </summary>
        private void CreateUserInfoAnim()
        {
            ShowUserInformation = new Storyboard();
            Storyboard.SetTargetName(ShowUserInformation, "UserInfo");
            Storyboard.SetTargetProperty(ShowUserInformation, new PropertyPath("Opacity"));
            DoubleAnimation da = new DoubleAnimation();
            da.Duration = new TimeSpan(0, 0, 1);
            da.From = 0.0;
            da.To = 1.0;

            //ElasticEase ee = new ElasticEase();
            //ee.EasingMode = EasingMode.EaseOut;
            //da.EasingFunction = ee;
            ShowUserInformation.Children.Add(da);
            LayoutRoot.Resources.Add("ShowUserInformation", ShowUserInformation);
        }

        public void UpdateCulture()
        {
            UserInfo.UpdateCulture();
            UpdateLoginBtn();
        }


        private void Authentication_LoggedIn(object sender, AuthenticationEventArgs e)
        {
            MainPageParent.BusyControl.IsBusy = true;
            if (!String.IsNullOrEmpty(WebContext.Current.User.Name))
            {
                SecurityServiceReference.SecurityServiceClient securitySvc = new SecurityServiceReference.SecurityServiceClient();
                securitySvc.LoadUserCompleted += new EventHandler<SecurityServiceReference.LoadUserCompletedEventArgs>(securitySvc_LoadUserCompleted);
                securitySvc.LoadUserAsync(WebContext.Current.User.Name);
            }
        }

        void securitySvc_LoadUserCompleted(object sender, SecurityServiceReference.LoadUserCompletedEventArgs e)
        {
            App.CurrentUser = e.Result;
            User = e.Result;
            OnLogin();
            MainPageParent.BusyControl.IsBusy = false;
        }

        private void Authentication_LoggedOut(object sender, AuthenticationEventArgs e)
        {
            User = null;
            App.CurrentUser = null;
            // Disconnect button appears
            UpdateCulture();
            // Raison logout event
            OnLogout();
        }

        private void TextBlock_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
        	
            if (!IsConnected)
            {
                LoginRegistrationWindow loginWindow = new LoginRegistrationWindow();
                loginWindow.Show();
            }
            else
            {
                Error dlgConfirm = new Error(LangHelper.GetString("ConfirmDisconnectTitle"), LangHelper.GetString("ConfirmDisconnect"), Error.ErrorType.Question);
                dlgConfirm.Closed += new EventHandler(dlgConfirm_Closed);
                dlgConfirm.Show();
            }			
			
        }

        private void LoginLogoutLink_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            MouseEnterStoryboard.Begin();
        }

        private void LoginLogoutLink_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            MouseLeaveStoryboard.Begin();
        }

	}
}